//
//  HybridViewController.swift
//  Test_Swift3.0
//
//  Created by alyadan on 2016/10/15.
//  Copyright © 2016年 alyadan. All rights reserved.
//

import MVVM_BaseViewController
import ObjectMapper
import SwiftyJSON
import SnapKit
import RxSwift

open class HybridViewController: HybridBaseViewController, UIWebViewDelegate {

    // MARK: temp area
    
    
    //MARK: --
    open override var currentModel: HybridVCModel {
        return vcModel.value as! HybridVCModel
    }
    
    lazy var hybridWebView: UIWebView = {
       
        let x = HybridWebView(hybrdViewModel: self.currentModel.hybridWebViewModel)
        return x
    }()
    
    
    open override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        currentModel.hybridVCDataModel.asObservable()
            .takeUntil(self.rx.methodInvoked(#selector(HybridViewController.viewWillDisappear(_:))))
            .bindNext {[unowned self] (x: HybridVCDataModel) in
                
                if let isHidden = x.isHideNavBar {
                    if isHidden {
                        self.setNavgationHidden(realHidden: true)
                    }else {
                        self.navigationController?.isNavigationBarHidden = false
                    }
                }
                if let color = x.navBgColor, color.characters.count != 0{
                    let hexColor = UIColor.init(HEXValue: color.hexIntegerValue())
                    self.navigationController?.navigationBar.setBackgroundImage(UIColor.createImage(color: hexColor, size: CGSize.init(width: 10, height: 10)), for: .default)
                }
                
                self.navigationController?.navigationBar.shadowImage = UIImage()
            }
            .addDisposableTo(disposeBag)
        
        
    }
    
    func customSetupUI() {
        if currentModel.hybridVCDataModel.value.bgClear == 0{
            self.view.backgroundColor = UIColor.black.withAlphaComponent(0.2)
        }
    }
    
    var commentView: SendMsgToolView?
    var searchBar: UISearchBar?
    
    open override func setupUI() {
        
        super.setupUI()
        view.addSubview(hybridWebView)
        customSetupUI()
        
        func setupWebView(){
            
            
            var hasSearchBar = false
            var hasCommentView = false
            
            if let searchBarParam = self.currentModel.hybridVCDataModel.value.searchBarParam, searchBarParam.count > 0 {
                
                hasSearchBar = true
                
                let x = UISearchBar()
                self.searchBar = x
                self.view.addSubview(x)
                
                x.snp.makeConstraints({[unowned self] (ConstraintMaker) in
                    ConstraintMaker.left.right.equalTo(self.view)
                    ConstraintMaker.top.equalTo(self.topLayoutGuide.snp.bottom)
                })
                
                x.placeholder = searchBarParam["title"] as? String
                x.rx.searchButtonClicked
                    .bindNext {[unowned self] in
                        HybridBaseHandler.callH5Method(hybridWebViewModel: self.currentModel.hybridWebViewModel, methodName: "cbSearchToUpdateH5Ui", param: ["searchContent": x.text!])
                    }
                    .addDisposableTo(disposeBag)
                
                x.rx.text
                    .map({ (text:String?) -> Bool in
                        if text == nil || text!.isEmpty {
                            return true
                        }
                        return false
                    })
                    .bindNext({[unowned self] (hidden:Bool) in
                        if hidden {
                            HybridBaseHandler.callH5Method(hybridWebViewModel: self.currentModel.hybridWebViewModel, methodName: "cbSearchClearToUpdateH5Ui", param: [:])
                            
                        }
                    })
                    .addDisposableTo(disposeBag)
                
                
            }
            
            if (currentModel.hybridVCDataModel.value.isHidenComment == false){
                hasCommentView = true
                
                let commentView = SendMsgToolView(viewModel: self.currentModel.commentViewModel)
                
                currentModel.commentViewModel.placeHolder.value = "请输入评论"
                
                self.commentView = commentView
                self.view.addSubview(commentView)
                
                //布局
                commentView.snp.makeConstraints({[unowned self] (ConstraintMaker) in
                    ConstraintMaker.left.bottom.right.equalTo(self.view)
                })
                
                
                //键盘监听
                NotificationCenter.default.rx.notification(Notification.Name.UIKeyboardWillChangeFrame)
                    .bindNext {[unowned self] (x: Notification) in
                        self.keyboardShow(notify: x)
                    }
                    .addDisposableTo(disposeBag)
                
            }
            
            //点击收回键盘
            self.hybridWebView.rx
                .methodInvoked(#selector(UIView.hitTest(_:with:)))
                .bindNext {[unowned self] (_) in
                    //输入框 回收
                    self.commentView?.endEditing(true)
                    
                    if let v = self.commentView, v.inputTextView.text == ""  {
                        self.currentModel.customData["parentId"] = nil
                        v.inputTextView.placeHolder().text =  self.currentModel.commentViewModel.firstPlaceHolder
                    }
                    
                    self.searchBar?.endEditing(true)
                    
                }
                .addDisposableTo(disposeBag)
            //end
            
            //Layout
            hybridWebView.snp.makeConstraints({[unowned self](ConstraintMaker) in
                
                
                
                ConstraintMaker.left.right.equalTo(self.view)
                
                if hasSearchBar {
                    ConstraintMaker.top.equalTo(self.searchBar!.snp.bottom).offset(-64)
                }else {
                    if MVVM_BaseViewController.viewBGImage != nil && self.currentModel.hybridVCDataModel.value.isHideNavBar == false{
                        ConstraintMaker.top.equalTo(self.view).offset(64)
                    }else {
                        ConstraintMaker.top.equalTo(self.view)
                    }
                }
                
                if hasCommentView {
                    ConstraintMaker.bottom.equalTo(self.commentView!.snp.top)
                }else{
                    ConstraintMaker.bottom.equalTo(self.view)
                }
                
            })
            
        }
        
        
        setupWebView()
        
        // other
        Hybrid_ObserveLifeCycle(hybridWebModels: [currentModel.hybridWebViewModel])
        
    }
    
    
    
    
    func keyboardShow(notify: Notification)  {
        guard let end =  notify.userInfo?["UIKeyboardFrameEndUserInfoKey"] as? CGRect else{
            return
        }
        
        guard let begin =  notify.userInfo?["UIKeyboardFrameBeginUserInfoKey"] as? CGRect else{
            return
        }
        
        guard let time =  notify.userInfo?["UIKeyboardAnimationDurationUserInfoKey"] as? Double else{
            return
        }
        
        
        var height = end.origin.y - begin.origin.y
        if height >= 0 {
            height = 0
        }else{
           height = end.height
        }
        
        
        let contentSize = self.hybridWebView.scrollView.contentSize
        UIView.animate(withDuration: time, delay: 0, options: .curveEaseOut, animations: {[unowned self] in
            self.commentView?.snp.updateConstraints {[unowned self] (ConstraintMaker) in
                ConstraintMaker.bottom.equalTo(self.view).offset(-height)
            }
            
            self.hybridWebView.scrollView.setContentOffset(CGPoint.init(x: 0, y: contentSize.height), animated: false)
            
            self.view.setNeedsLayout()
            self.view.layoutIfNeeded()
            //to do
            }, completion:nil)
        
    }
    
    open override func addActionTarget() {
        
        super.addActionTarget()
        
    }
    
    open override func bindModelData() {
        
        //navigationBar
        currentModel.hybridVCDataModel
        .asObservable()
            .bindNext {[unowned self] (dataModel:HybridVCDataModel) in
                
                
                
                if let rightParam = JSON(dataModel.rightParam).array{
                    
                    if  rightParam.count > 0 {
                        if let param = rightParam[0].dictionaryValue["param"]?.string,
                            let type = rightParam[0].dictionaryValue["type"]?.int {
                            
                            if type == 1 {
                                self.setNavgationItem(withImageName: param, orTitle: nil, location: .right)
                            }else{
                                self.setNavgationItem(withImageName: nil, orTitle: param, location: .right)
                            }
                            
                        }
                        
                    }
                    
                }
                
                if let leftParam = JSON(dataModel.leftParam).array{
                    
                    if  leftParam.count > 0 {
                        
                        if let param = leftParam[0].dictionaryValue["param"]?.string,
                            let type = leftParam[0].dictionaryValue["type"]?.int {
                            
                            if type == 1 {
                                self.setNavgationItem(withImageName: param, orTitle: nil, location: .left)
                            }else{
                                self.setNavgationItem(withImageName: nil, orTitle: param, location: .left)
                            }
                            
                        }
                        
                    }
                    
                }
            }
            .addDisposableTo(disposeBag)
        
    }
    
    
}


public class HybridVCModel:  HybridBaseVCModel{
    
    var hybridVCDataModel: Variable<HybridVCDataModel>
    
    public lazy var commentViewModel:SendMsgToolViewModel = {
        
        let x =  SendMsgToolViewModel(parentViewModel: self)
        
        x.sendMsgBlock = {[unowned self] msg in
            HybridBaseHandler.callH5Method(hybridWebViewModel: self.hybridWebViewModel, methodName: "cbSendComment", param: ["content":msg ,"parentId": self.customData["parentId"] ?? 0])
           self.customData["parentId"]  = nil
        }
        
        return x
    }()
    
    public func popCommentView(){
       (MVVM_modelController as? HybridViewController)?.commentView?.inputTextView.becomeFirstResponder()
    }
    
    public lazy var hybridWebViewModel:HybridWebViewModel =
        HybridWebViewModel(parentViewModel: self,
                           htmlName: self.hybridVCDataModel.value.url)
    
    public init(parentViewModel: MVVM_BaseViewModel?, dataModel:HybridVCDataModel) {
        
        self.hybridVCDataModel = Variable<HybridVCDataModel>(dataModel)
        super.init(parentViewModel: parentViewModel)
    }
    
    
    public override func setupModel() {
        
        hybridVCDataModel.asObservable()
            .bindNext {[unowned self] (x: HybridVCDataModel) in
                if x.centerParam != nil {
                    
                    let centerParam = JSON(x.centerParam!).array
                    
                    if centerParam != nil ,centerParam!.count > 0 {
                        self.viewControllerTitle.value = centerParam?[0].dictionary?["param"]?.stringValue ?? ""
                    }
                    
                }
            }
            .addDisposableTo(disposeBag)
        
    }
    
    
    public override func onTapNavLeftBtn() {
        if let leftParam = JSON(hybridVCDataModel.value.leftParam!).array{
            if  leftParam.count > 0 {
                if let leftType = leftParam[0].dictionaryValue["leftType"]?.string{
                    if leftType == "1"{
                        HybridBaseHandler.callH5Method(hybridWebViewModel: self.hybridWebViewModel, methodName: "tapNavLeftBtn", param: [:])
                        return
                    }
                }
            }
        }
        
        super.onTapNavLeftBtn()
    }
    
    public override func onTapNavRightBtn() {
        HybridBaseHandler.callH5Method(hybridWebViewModel: hybridWebViewModel, methodName: "tapNavRightBtn", param: [:])
    }
    
    //MARK: override
    public override  func viewController(vcIndex: Int) -> MVVM_BaseViewController? {
        return HybridViewController()
        
    }
    
    
    override public var hybridVCDataModels: [HybridVCDataModel] {
        return [self.hybridVCDataModel.value]
    }
}



